import time

from tools import ImageUtil, ActionUtil, ColorUtil, WindowUtil
from word_map import WordMap


class Switch:
    def __init__(self, position_grab, map_name):

        self.word_map = WordMap()

        self.map_name = map_name

        self.position_grab = position_grab

        self.switch_role_img = "images/switch_role.bmp"

        self.start_battle_img = "images/start_battle.bmp"

        self.tips_img = "images/tips.bmp"

        self.confirm_img = "images/confirm.bmp"

        self.close_img = "images/close2.bmp"

        self.no_stamina_img = "images/no_stamina.bmp"

        self.select_difficulty_img = "images/map/select_difficulty.bmp"

        # 是否更换了角色
        self.is_Switch = False

    def current_role_to_go(self, position_grab):
        window = WindowUtil.grab_screen(position_grab)
        locs = [(105, 79), (105, 83), (110, 80), (108, 77)]
        colors = [(199, 0, 13), (198, 0, 12), (140, 11, 22), (121, 10, 17)]
        strength_flag = ColorUtil.check_colors_similar(ColorUtil.cv2pil(window), locs, colors)
        if strength_flag:
            print("当前角色没有体力，准备更换角色")
            return False
        else:
            print("当前角色有体力，准备进入关卡")
            # 打开小地图
            ActionUtil.mouse_left_click(self.word_map.mini_loc)
            time.sleep(3)
            # 查询路径
            path, icon, target = self.word_map.get_path(self.map_name)
            # 判断当前小地图是否可以直接进入
            window = WindowUtil.grab_screen(position_grab)
            flag, loc = ImageUtil.is_icon_exist(window, icon, (0, 0))
            if flag:
                # 可以，则直接进入
                path = path[-1:]
            # 依次点击，进图
            for index, node in enumerate(path):
                print(f"path: {node}")
                ActionUtil.mouse_left_click(node.get("loc"))
                time.sleep(3)
            # 监视是否可以选关卡
            while True:
                window = WindowUtil.grab_screen(position_grab)
                flag, loc = ImageUtil.is_icon_exist(window, self.select_difficulty_img, (0, 0))
                if flag:
                    break
                else:
                    print("自动寻路中，继续等待", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
                    time.sleep(2)
            # 选关卡
            for index, loc in enumerate(target):
                ActionUtil.mouse_left_click(loc)
                time.sleep(2)
            return True

    def current_role_start_battle(self, position_grab):
        window = WindowUtil.grab_screen(position_grab)
        flag, loc = ImageUtil.is_icon_exist(window, self.start_battle_img, (40, 15))
        print(f"[start_battle]: {flag} {loc}")
        if not flag:
            return False
        else:
            ActionUtil.mouse_left_click((loc[0], loc[1]))
            time.sleep(2)

            # 如果出现[本次登录期间不再显示]，则先确认
            window = WindowUtil.grab_screen(position_grab)
            flag, loc = ImageUtil.is_icon_exist(window, self.tips_img, (90, 15))
            print(f"[tips_img]: {flag} {loc}")
            if flag:
                ActionUtil.mouse_left_click((loc[0], loc[1]))
                time.sleep(2)

                flag, loc = ImageUtil.is_icon_exist(window, self.confirm_img, (15, 15))
                print(f"[confirm_img]: {flag} {loc}")
                if flag:
                    print("开始战斗！！！")
                    ActionUtil.mouse_left_click((loc[0], loc[1]))
                    time.sleep(2)
                    return True
            else:
                print("开始战斗！！！")
                return True

    def switch_role(self, window):
        # ========================1、当前角色没有体力，打开"选角"窗口==========================
        # window = WindowUtil.grab_screen(position_grab)
        flag, loc = ImageUtil.is_icon_exist(window, self.switch_role_img, (20, 6))
        print(f"[switch_role_img]: {flag} {loc}")
        if not flag:
            return False
        else:
            ActionUtil.mouse_left_click((loc[0], loc[1]))
            time.sleep(2)

            # ========================2、寻找可用角色=======================================
            available_flag, available_loc = self.find_role()
            if available_flag:
                # 选择角色
                ActionUtil.mouse_left_click(available_loc)
                time.sleep(2)
                # 开始游戏
                ActionUtil.mouse_left_click((820, 505))
                time.sleep(10)
            else:
                print("未找到可用的角色，准备退出脚本，see you tomorrow")
            return available_flag

    def find_role(self, find_count=3, slide_count=1):
        available_flag, available_loc = False, None
        _slide = 1
        while True:
            # 当前选择角色的窗口，寻找有体力的角色
            _count = 1
            window = WindowUtil.grab_screen(self.position_grab)
            while True:
                # 尝试3次，判断是否有体力(体力值是否为白色)
                available_flag, available_loc = ColorUtil.find_one_coordinate(ColorUtil.cv2pil(window),
                                                                              (290, 120),
                                                                              (350, 440),
                                                                              (234, 226, 205))
                if available_flag or _count > find_count:
                    break
                else:
                    print(f"尝试识别有效体力值: {_count}")
                    _count += 1
                    time.sleep(1)

            # 找到了就返回，否则滑动窗口，继续寻找
            if available_flag or _slide > slide_count:
                break
            else:
                print("未找到有效角色，滑动窗口，继续寻找")
                _slide += 1
                ActionUtil.slide_screen_up()
                time.sleep(3)

        return available_flag, available_loc

    def switch_main(self):
        # 判断是否在城外的界面
        window = WindowUtil.grab_screen(self.position_grab)
        flag, loc = ImageUtil.is_icon_exist(window, self.switch_role_img, (0, 0))
        print(f"[是否在城镇界面]: {flag} {loc}")
        if not flag:
            # 如果有别的窗口，则关闭
            flag, loc = ImageUtil.is_icon_exist(window, self.close_img, (11, 11))
            print(f"[close_img]: {flag} {loc}")
            if flag:
                ActionUtil.mouse_left_click((loc[0], loc[1]))
            time.sleep(1)
            return True, 2
        # 延迟1秒，等待画面稳定，增加图色识别的准确率
        time.sleep(1)
        # 1、判断是角色否有体力(体力值是否为红色)，然后开始战斗
        if self.current_role_to_go(self.position_grab):
            flag = self.current_role_start_battle(self.position_grab)
            if flag:
                # 恢复默认值
                self.is_Switch = False
                return True, 1
            else:
                return True, 2
        else:
            # 2、打开选角窗口，查找可用角色
            if self.switch_role(window):
                # 已更换角色
                self.is_Switch = True
                return True, 2
            else:
                return False, 2
